﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SeaBattle.UI.Web.Models;
using SeaBattle.Domain.Abstract.Services;
using SeaBattle.Domain.Entities;

namespace SeaBattle.UI.Web.Controllers
{
    public class GameController : Controller
    {
        private IGameService gameService;
        private IPlayerService playerService;
        private IAccountService AccountService;


        public GameController(IGameService gameService, IPlayerService playerService, IAccountService AccountService)
        {
            this.gameService = gameService;
            this.playerService = playerService;
            this.AccountService = AccountService;
        }
        //
        // GET: /Game/

        [Authorize]
        public ActionResult Index(int id)
        {
            // Get Game
            var game = gameService.GetGameById(id);
            var me = playerService.GetPlayer(User.Identity.Name);
            if(game==null || (game.Opponent == null && game.Creator==me))
                return RedirectToAction("Index", "Room");
            if (game.Playing || game.Closed)
                return RedirectToAction("Index", "Play", new { id = id });
            if (game.Creator == me && game.Opponent==null)
                RedirectToAction("Index", "Room");
            if (game.Opponent == null)
            {
                Account account = AccountService.GetPlayerAccount(me.Login);
                if (account.Balance < game.Preset)
                    return RedirectToAction("Index","Room");
                account.AddAmount(-game.Preset);
                game.JoinOpponent(me);
            }
            Session["SetGame"] = game;
            return View(new GameViewModel { Game = game, player = me });
        }

        [Authorize]
        public string TryAdd(string Arg)
        {            
            Game game=(Game)Session["SetGame"];
            if (game.State != GameState.STATE_BOARD_SETUP)
                return "Game began. Refresh your page.";
            if (game == null)
                return "TimeOut. Refresh your page.";
            return game.TryPrepareFleet(playerService.GetPlayer(User.Identity.Name), Arg);            
        }

        [Authorize]
        public string SearchOpponent()
        {
            Player player = playerService.GetPlayer(User.Identity.Name);
            Game game=(Game)Session["SetGame"];
            if (game == null)
                return "TimeOut. Refresh your page.";
            bool FleetCreated;
            if (player == game.Creator)
                FleetCreated = game.OpponentFleetInitialized;
            else
                FleetCreated = game.CreatorFleetInitialized;
            return FleetCreated ? "true" : "false";
        }
    }
}
